package com.miaoquan.mqapitbk.service.impl;

import com.miaoquan.mqapitbk.service.TklService;
import com.miaoquan.mqcommon.exception.ApiException;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkTpwdCreateRequest;
import com.taobao.api.response.TbkTpwdCreateResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 淘口令Service实现类
 *
 * @author Fa
 * @date 2020-04-03 16:34
 */
@Service
public class TklServiceImpl implements TklService {

    @Autowired
    private TaobaoClient taobaoClient;

    @Override
    public String createTkl(String userId, String text, String url, String logo) throws ApiException {
        TbkTpwdCreateRequest req = new TbkTpwdCreateRequest();
        req.setUserId(userId);
        req.setText(text);
        if (!StringUtils.isEmpty(url)) {
            url = url.replaceFirst("^(//|(http(s|)://)|)", "https://");
        }
        req.setUrl(url);
        req.setLogo(logo);
        TbkTpwdCreateResponse rsp = null;
        try {
            rsp = taobaoClient.execute(req);
        } catch (com.taobao.api.ApiException e) {
            throw new ApiException(e);
        }
        if (rsp.isSuccess()) {
            return rsp.getData().getModel();
        }
        return "";
    }
}
